package luke.ui.components;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

import java.util.Map;
import java.util.List;
import java.util.ArrayList; // 添加这个导入

import luke.core.controller.PlayController;
import luke.core.utils.SvgIconLoader;
import luke.core.utils.LanguageManager; // 新增：导入LanguageManager

// 导入PlaybackStateManager
import luke.core.utils.PlaybackStateManager;
import luke.core.utils.AppStateManager; // 新增：导入AppStateManager


public class FileListPanel extends JPanel {
    private final PlayController playController;
    private JList<File> fileList;
    private DefaultListModel<File> listModel;
    private DefaultListModel<File> filteredListModel;
    List<File> sharedSelectedFiles;
    private JTextField searchField;
    private JCheckBox selectAllCheckBox;
    private luke.ui.main.RunBeatsUI mainUI;
    private Map<File, luke.audio.metadata.Song> songData; // 歌曲数据引用
    private luke.ui.components.PlayPanel playPanel; // 播放面板引用

    // 添加PlaybackStateManager引用
    private PlaybackStateManager playbackStateManager;
    
    // 添加AppStateManager引用
    private AppStateManager appStateManager;
    
    // 添加LanguageManager引用
    private LanguageManager languageManager;

    public interface SelectionChangeListener {
        void onSelectionChanged();
    }

    public FileListPanel() {
        // 初始化LanguageManager
        this.languageManager = LanguageManager.getInstance();

        // 初始化PlaybackStateManager并注册为监听器
        this.playbackStateManager = PlaybackStateManager.getInstance();
        this.playbackStateManager.addListener(new PlaybackStateManager.PlaybackStateListener() {
            @Override
            public void onPlaybackStateChanged(boolean isPlaying) {
                // 播放状态改变时刷新整个列表
                fileList.repaint();
            }

            @Override
            public void onFileChanged(File file) {
                // 播放文件改变时刷新整个列表
                fileList.repaint();
            }
        });
        playController = PlayController.getInstance();

        // 初始化AppStateManager并注册为监听器
        this.appStateManager = AppStateManager.getInstance();
        this.sharedSelectedFiles= appStateManager.getSharedSelectedFiles();
        this.appStateManager.addListener(new AppStateManager.StateListener() {
            @Override
            public void onSearchTextChanged(String searchText) {
                // 当搜索文本改变时，更新搜索框文本并过滤列表
                searchField.setText(searchText);//搜索框文本发生变化会自动触发过滤
            }



            //当已选择列表发生变化时调用
            @Override
            public void onSelectedFilesChanged() {
                // 当已选择列表发生变化时，更新选择状态
                handleSelectionChanged();
            }
        });



        setLayout(new BorderLayout());
        setBorder(BorderFactory.createTitledBorder(languageManager.getPanelText("file.list.title")));
        // 设置固定的最小和最大尺寸，避免UI跳动
        setMinimumSize(new Dimension(300, 200));
        setPreferredSize(new Dimension(350, 600));
        setMaximumSize(new Dimension(500, Short.MAX_VALUE));

        // 初始化文件列表模型
        listModel = new DefaultListModel<>();
        filteredListModel = new DefaultListModel<>();
        this.sharedSelectedFiles = sharedSelectedFiles;

        // 创建搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        // 搜索图标标签
        JLabel searchIconLabel = new JLabel();
        SvgIconLoader.setButtonIcon(searchIconLabel, "/ico/搜索.svg", 16, 16);
        searchIconLabel.setToolTipText(languageManager.getPanelText("file.list.search.tooltip"));
        searchIconLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        searchPanel.add(searchIconLabel);

        // 搜索文本框 - 实时搜索
        searchField = new JTextField(20);
        searchField.setToolTipText(languageManager.getPanelText("file.list.search.placeholder"));
        searchField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                filterSongList();
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                filterSongList();
            }

            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                filterSongList();
            }
        });
        searchPanel.add(searchField);

        // 清除输入按钮
        JLabel clearSearchButton = new JLabel();
        SvgIconLoader.setButtonIcon(clearSearchButton, "/ico/清除输入.svg", 16, 16);
        clearSearchButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        clearSearchButton.setToolTipText(languageManager.getPanelText("file.list.clear.tooltip"));
        clearSearchButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                searchField.setText("");
                //因为搜索框的输入变化会自动触发过滤，所以这里不需要再次调用filterSongList()
//                filterSongList();
            }
        });
        searchPanel.add(clearSearchButton);

        // 全选复选框
        selectAllCheckBox = new JCheckBox(languageManager.getPanelText("file.list.select.all"), false);
        selectAllCheckBox.addActionListener(e -> {
            selectAllFiles(selectAllCheckBox.isSelected());
        });
        searchPanel.add(selectAllCheckBox);

        // 创建文件列表
        fileList = new JList<>(filteredListModel);
        fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fileList.setCellRenderer(new CheckboxListCellRenderer());
        fileList.setBorder(BorderFactory.createEmptyBorder());

        // 移除固定宽度设置，使用自适应宽度
        // fileList.setFixedCellWidth(300);

        // 添加鼠标点击事件处理
        fileList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int index = fileList.locationToIndex(e.getPoint());
                if (index >= 0) {
                    File file = filteredListModel.getElementAt(index);

                    // 检测是否点击了播放按钮区域
                    Rectangle cellBounds = fileList.getCellBounds(index, index);
                    if (cellBounds != null) {
                        int x = e.getX() - cellBounds.x;

                        // 复选框大约占20像素，播放按钮大约占20像素
                        if (x >= 25 && x <= 45) { // 播放按钮区域（估算）
                            // 点击的是播放按钮，处理播放/停止逻辑
                            playController.setInputCurrentFile(file);
                            playController.togglePlayback();
                            return; // 不处理选择逻辑
                        }
                    }

                    toggleFileSelection(file);
                }
            }
        });

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(fileList);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());

        // 添加组件到主面板
        add(searchPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }

    // 过滤歌曲列表方法
    private void filterSongList() {
        String searchText = searchField.getText().toLowerCase().trim();
        DefaultListModel<File> newModel = new DefaultListModel<>();

        for (int i = 0; i < listModel.getSize(); i++) {
            File file = listModel.getElementAt(i);
            if (searchText.isEmpty() || file.getName().toLowerCase().contains(searchText)) {
                newModel.addElement(file);
            }
        }

        filteredListModel = newModel;
        fileList.setModel(filteredListModel);
        updateSelectAllCheckboxState();// 更新全选复选框状态
    }

    // 添加文件到列表
    public void addFile(File file) {
        listModel.addElement(file);// 添加到原始列表模型
        filterSongList();// 过滤列表
    }

    // 清空文件列表
    public void clearFiles() {
        listModel.clear();
        filteredListModel.clear();
        sharedSelectedFiles.clear();
        fileList.setModel(filteredListModel);
    }

    // 切换文件选择状态
    public void toggleFileSelection(File file) {
        if (sharedSelectedFiles.contains(file)) {
            sharedSelectedFiles.remove(file);
        } else {
            sharedSelectedFiles.add(file);
        }
        notifySelectionChanged();// 更新AppStateManager中的selectedFiles
    }

    // 处理选择变化（统一调用）
    private void handleSelectionChanged() {
        fileList.repaint();
        updateSelectAllCheckboxState();
    }

    // 更新全选复选框状态
    private void updateSelectAllCheckboxState() {
        // 检查过滤后的所有文件是否都被选中
        boolean allSelected = true;
        for (int i = 0; i < filteredListModel.getSize(); i++) {
            if (!sharedSelectedFiles.contains(filteredListModel.getElementAt(i))) {
                allSelected = false;
                break;
            }
        }
        selectAllCheckBox.setSelected(allSelected);// 更新复选框状态
    }

    // 全选/取消全选
    public void selectAllFiles(boolean select) {
        if (select) {
            for (int i = 0; i < filteredListModel.getSize(); i++) {
                File file = filteredListModel.getElementAt(i);
                if (!sharedSelectedFiles.contains(file)) {
                    sharedSelectedFiles.add(file);
                }
            }
        } else {
            // 只取消选择过滤后的文件
            List<File> filesToRemove = new ArrayList<>();
            for (int i = 0; i < filteredListModel.getSize(); i++) {
                File file = filteredListModel.getElementAt(i);
                if (sharedSelectedFiles.contains(file)) {
                    filesToRemove.add(file);
                }
            }
            sharedSelectedFiles.removeAll(filesToRemove);
        }
        notifySelectionChanged();// 更新AppStateManager中的selectedFiles
    }

    /**
     * 通知选择变化
     */
    private void notifySelectionChanged() {
        appStateManager.updateSelectedFiles();
    }


    // 内部类：复选框列表单元格渲染器
    private class CheckboxListCellRenderer extends JPanel implements ListCellRenderer<File> {
        private JCheckBox checkBox;
        private JLabel playButton;
        private JLabel label;
        private JLabel bpmLabel;

        private boolean isFilePlaying(File file) {
            // 检查文件是否正在播放
            if (playbackStateManager != null) {
                File currentFile = playbackStateManager.getCurrentFile();
                boolean isPlaying = playbackStateManager.isPlaying();
                return currentFile != null && currentFile.equals(file) && isPlaying;
            }
            return false;
        }

        public CheckboxListCellRenderer() {
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
            setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
            checkBox = new JCheckBox();
            checkBox.setEnabled(false);

            playButton = new JLabel();
            playButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

            label = new JLabel();
            // 设置最大宽度以防止过长文件名影响布局
            label.setMaximumSize(new Dimension(200, Integer.MAX_VALUE));

            bpmLabel = new JLabel();
            bpmLabel.setForeground(new Color(27, 121, 148));
            bpmLabel.setFont(bpmLabel.getFont().deriveFont(11.0f));
            bpmLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
            // 设置固定宽度以确保BPM信息对齐
            bpmLabel.setMinimumSize(new Dimension(70, 0));
            bpmLabel.setPreferredSize(new Dimension(70, 0));
            bpmLabel.setMaximumSize(new Dimension(100, 100));

            add(checkBox);
            add(Box.createRigidArea(new Dimension(5, 0)));
            add(playButton);
            add(Box.createRigidArea(new Dimension(5, 0)));
            add(label);
            add(Box.createHorizontalGlue());
            add(bpmLabel);
            setOpaque(true);
        }

        @Override
        public Component getListCellRendererComponent(JList<? extends File> list, File value,
                                                      int index, boolean isSelected, boolean cellHasFocus) {

            // 设置文件名
            String fileName = value.getName();
            if (fileName.length() > 30) {
                label.setText(fileName.substring(0, 27) + "...");
                label.setToolTipText(fileName);
            } else {
                label.setText(fileName);
                label.setToolTipText(null);
            }

            // 设置复选框状态
            checkBox.setSelected(sharedSelectedFiles.contains(value));

            // 设置播放按钮图标（根据是否正在播放当前文件）
            // 修复图标逻辑，使其与PlayPanel保持一致：
            // 播放时显示暂停图标，暂停/停止时显示播放图标
            if (isFilePlaying(value)) {
                // 文件正在播放，显示暂停图标
                SvgIconLoader.setButtonIcon(playButton, "/ico/暂停.svg", 16, 16);
                playButton.setToolTipText(languageManager.getPanelText("file.list.pause.tooltip"));
            } else {
                // 文件未播放，显示播放图标
                SvgIconLoader.setButtonIcon(playButton, "/ico/播放.svg", 16, 16);
                playButton.setToolTipText(languageManager.getPanelText("file.list.play.tooltip"));
            }

            // 设置背景色
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                label.setForeground(list.getSelectionForeground());
                bpmLabel.setForeground(Color.WHITE);
            } else {
                setBackground(list.getBackground());
                label.setForeground(list.getForeground());
                bpmLabel.setForeground(new Color(27, 121, 148));
            }

            return this;
        }
    }
}